package com.example.springbootdemo.web;

import com.example.springbootdemo.DemoProperties;
import com.example.springbootdemo.mapper.DemoMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@RestController
public class HelloAction {

    @RequestMapping({"hello"})
    public String hello(){
        return "你好中国!";
    }

    @Resource
    DemoProperties demoProperties;

    @GetMapping("props")
    DemoProperties showProperties(){
        return demoProperties;
    }

    @Resource
    DemoMapper demoMapper;

    @GetMapping("jobs")
    List<?> queryJobs(){
        return demoMapper.selectJobs();
    }

    @RequestMapping("showJob")
    ModelAndView showJob(ModelAndView mav){
        List<Map<String, Object>> jobs = demoMapper.selectJobs();
        mav.setViewName("jobs");
        mav.addObject("jobs", jobs);
        return mav;
    }

    @Resource
    MailAction mailAction;

    @RequestMapping("forgetPwd")
    String forgetPwd(String name, HttpSession session){
        Map<String, Object> user = demoMapper.selectByName(name);
        String to = (String) user.get("email");
        String title = "验证码邮件";
        String vcode = System.currentTimeMillis() + "";
        vcode = vcode.substring(vcode.length()-4);
        String content = "忘记密码, 您的验证码是: " + vcode;
        session.setAttribute("vcode",vcode);
        session.setAttribute("uname",name);
        return mailAction.sendEmail(to,title,content);
    }
    @RequestMapping("resetPwd")
    String resetPwd(String rcode, String pwd1, String pwd2,
                    @SessionAttribute(required = false) String vcode,
                    @SessionAttribute(required = false) String uname){
        if(vcode==null){
            return "请先发送验证码!";
        }
        if(rcode==null){
            return "请输入验证码!";
        }
        if(rcode.equals(vcode) == false){
            return "请输入正确的验证码!";
        }
        if(pwd1.equals(pwd2) == false){
            return "确认密码错误!";
        }
        demoMapper.updatePwd(uname, pwd1);
        return "密码修改成功!";
    }

}
